package com.example.glide_pre_demo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.glide_pre_demo.R;

public class ImageAdapter extends ArrayAdapter {
    private Context mContext;
    private LayoutInflater mInflater;
    private String[] mImageUrls;

    public ImageAdapter(Context context, String[] imageUrls) {
        super(context, R.layout.listview_item_image, imageUrls);
        this.mContext = context;
        this.mImageUrls = imageUrls;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
//        if (convertView == null) {
//            convertView = mInflater.inflate(R.layout.listview_item_image, parent, false);
//            holder = new ViewHolder();
//            holder.iv = (ImageView) convertView.findViewById(R.id.iv);
//            convertView.setTag(holder);
//        } else {
//            holder = (ViewHolder) convertView.getTag();
//        }

        // You must not call setTag() on a view Glide is targeting
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.listview_item_image, parent, false);
        }
        holder = new ViewHolder();
        holder.iv = (ImageView) convertView.findViewById(R.id.iv);

        Glide.with(mContext)
                .load(mImageUrls[position])
                // 加载过程中显示的占位符图片
                .placeholder(R.mipmap.ic_launcher)
                // 加载失败时显示的图片
                .error(R.mipmap.ic_launcher)
                // 不进行内存缓存
//                .skipMemoryCache(true)
                // 硬盘缓存策略
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                // 不进行硬盘缓存
//                .diskCacheStrategy(DiskCacheStrategy.NONE)
                // 淡入淡出的动画效果
                .crossFade()
                // 不显示任何动画效果
//                .dontAnimate()
                .priority(Priority.HIGH)
                .into(holder.iv);

        return convertView;
    }

    private static class ViewHolder {
        ImageView iv;
    }
}